package com.rongshu.view.userInfo.activity;

import android.Manifest;
import android.content.Intent;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.view.View;
import android.widget.TextView;

import com.rongshu.R;
import com.rongshu.utils.Common;
import com.rongshu.utils.Constant;
import com.rongshu.utils.UserInfoUtils;
import com.rongshu.view.base.BaseActivity;
import com.rongshu.view.base.mvp.INetBean;
import com.rongshu.view.userInfo.entity.ThirdPartyInfo;
import com.rongshu.view.userInfo.iview.ThirdBindView;
import com.rongshu.view.userInfo.presenter.ThirdBindPresenter;
import com.rongshu.widget.BanyanDialog;
import com.umeng.socialize.UMAuthListener;
import com.umeng.socialize.UMShareAPI;
import com.umeng.socialize.bean.SHARE_MEDIA;
import com.utils.Utils;
import com.utils.permissions.OnPermission;
import com.utils.permissions.XXPermissions;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;

public class ThirdBindingActivity extends BaseActivity<ThirdBindPresenter> implements ThirdBindView {
    @BindView(R.id.txt_top_title)
    TextView txt_top_title;//标题
    @BindView(R.id.txt_bound_qq)
    TextView txt_bound_qq;
    @BindView(R.id.txt_bound_weixin)
    TextView txt_bound_weixin;
    @BindView(R.id.txt_bound_xinlang)
    TextView txt_bound_xinlang;
    //map
    private Map<String, Object> map = null;
    //第三方登录api
    private UMShareAPI mShareAPI = null;
    //boolean
    private boolean isBoundQQ = false, isBoundWX = false, isBoundXL;
    //dialog 第三方账号解绑使用
    private BanyanDialog banyanInputDialog = null;
    //type
    private int type = 0;
    //phone
    private String phone = null;
    //bean
    private ThirdPartyInfo.ResponseBean bean = null;
    //permission
    private String[] mPermissionList = new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE,
            Manifest.permission.READ_EXTERNAL_STORAGE};

    @Override
    protected int initLayout() {
        return R.layout.activity_third_binding_view;
    }

    @Override
    protected void initView() {
        //set presenter
        setPresenter(new ThirdBindPresenter(this), this);
        //phone
        if (getIntent() != null) {
            phone = getIntent().getStringExtra(Constant.INTENT_MESSAGE);
        }
        //设置title
        txt_top_title.setText(R.string.setting_third_binding);
    }

    @Override
    protected void initData() {

    }

    @Override
    protected void updateViews(boolean isRefresh) {
        getThirdParty();
    }

    /**
     * 更新view
     */
    private void refreshView() {
        txt_bound_qq.setText(isBoundQQ ? bean.getQq() : getString(R.string.not_bound));
        txt_bound_qq.setTextColor(isBoundQQ ? getResources().getColor(R.color.color_4a4a4a) : getResources().getColor(R.color.color_9f9f9f));
        txt_bound_weixin.setText(isBoundWX ? bean.getWechat() : getString(R.string.not_bound));
        txt_bound_weixin.setTextColor(isBoundWX ? getResources().getColor(R.color.color_4a4a4a) : getResources().getColor(R.color.color_9f9f9f));
        txt_bound_xinlang.setText(isBoundXL ? bean.getWeibo() : getString(R.string.not_bound));
        txt_bound_xinlang.setTextColor(isBoundXL ? getResources().getColor(R.color.color_4a4a4a) : getResources().getColor(R.color.color_9f9f9f));
    }

    /**
     * 获取第三方账号绑定信息和实名认证信息
     */
    private void getThirdParty() {
        int user_id = UserInfoUtils.getUserId();
        map = new HashMap<>();
        map.put("user_id", user_id);
        presenter.getThirdParty(user_id, Common.encryptionSign(map));
        map.clear();
    }

    /**
     * 第三方账户绑定
     */
    private void getBindingQQWechatWeiBo(int type, String open, String nickname) {
        int user_id = UserInfoUtils.getUserId();
        map = new HashMap<>();
        map.put("user_id", user_id);
        map.put("type", type);
        map.put("open", open);
        map.put("nickname", nickname);
        presenter.getBindingQQWechatWeiBo(user_id, type, open, nickname, Common.encryptionSign(map));
        map.clear();
    }

    /**
     * 第三方账户解绑
     */
    private void getUnlinkQQWechatWeiBo(int type) {
        int user_id = UserInfoUtils.getUserId();
        map = new HashMap<>();
        map.put("user_id", user_id);
        map.put("type", type);
        presenter.getUnlinkQQWechatWeiBo(user_id, type, Common.encryptionSign(map));
        map.clear();
    }


    /**
     * 第三方账号解绑使用dialog
     */
    public void showUnBoundHint(final int type) {
        //dialog
        BanyanDialog.Builder builder = new BanyanDialog.Builder(this);
        builder.setTitle("提示");
        builder.setContent(type == 1 ? "确定要解绑QQ嘛" : type == 2 ? "确定要解绑微信嘛" : "确定要解绑新浪微博嘛");
        builder.setLeft("取消");
        builder.setRight("确定");
        builder.setDialogOnClick(new BanyanDialog.Builder.onClickListener() {
            @Override
            public void leftClickListener() {
                banyanInputDialog.dismiss();
            }

            @Override
            public void rightClickListener() {
                banyanInputDialog.dismiss();
                //解绑
                getUnlinkQQWechatWeiBo(type);
            }
        });
        banyanInputDialog = builder.create();
        banyanInputDialog.show();
    }


    @OnClick({R.id.layout_back, R.id.layout_qq_bound, R.id.layout_weixin_bound, R.id.layout_xinlang_bound})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.layout_back:
                finish();
                break;
            case R.id.layout_qq_bound:
                type = 1;
                if (isBoundQQ) {
                    // new
                    if (TextUtils.isEmpty(phone)) {
                        toast("第三方登录不可解绑");
                        return;
                    }
                    showUnBoundHint(type);
                } else {
                    bindThirdAccount();
                }
                break;
            case R.id.layout_weixin_bound:
                type = 2;
                if (isBoundWX) {
                    // new
                    if (TextUtils.isEmpty(phone)) {
                        toast("第三方登录不可解绑");
                        return;
                    }
                    showUnBoundHint(type);
                } else {
                    bindThirdAccount();
                }
                break;
            case R.id.layout_xinlang_bound:
                type = 3;
                if (isBoundXL) {
                    // new
                    if (TextUtils.isEmpty(phone)) {
                        toast("第三方登录不可解绑");
                        return;
                    }
                    showUnBoundHint(type);
                } else {
                    bindThirdAccount();
                }
                break;
        }
    }

    /**
     * 第三方账号登录绑定
     */
    private void bindThirdAccount() {
        if (type == 3) {
            if (!Utils.isWBInstall(this)) {
                toast("\"新浪微博\"不可用\n请检查手机是否安装\"新浪微博\"");
                return;
            }
        }
        mShareAPI = UMShareAPI.get(getApplicationContext());
        if (!XXPermissions.isHasPermission(this, mPermissionList)) {
            XXPermissions.with(this).permission(mPermissionList).request(new OnPermission() {
                @Override
                public void hasPermission(List<String> granted, boolean isAll) {
                    mShareAPI.deleteOauth(ThirdBindingActivity.this,
                            type == 1 ? SHARE_MEDIA.QQ : type == 2 ? SHARE_MEDIA.WEIXIN : SHARE_MEDIA.SINA, authListener);
                }

                @Override
                public void noPermission(List<String> denied, boolean quick) {
                }
            });
        } else {
            mShareAPI.deleteOauth(this,
                    type == 1 ? SHARE_MEDIA.QQ : type == 2 ? SHARE_MEDIA.WEIXIN : SHARE_MEDIA.SINA, authListener);
        }
    }

    /**
     * 登录监听
     */
    private UMAuthListener authListener = new UMAuthListener() {
        @Override
        public void onStart(SHARE_MEDIA share_media) {

        }

        @Override
        public void onComplete(SHARE_MEDIA share_media, int i, Map<String, String> map) {
            if (map != null) {
                //类别(1QQ 2微信 3微博)
                //用户唯一标识
                String open = "";
                switch (share_media) {
                    case QQ:
                        type = 1;
                        open = map.get("openid");
                        break;
                    case WEIXIN:
                        type = 2;
                        open = map.get("openid");
                        break;
                    case SINA:
                        type = 3;
                        open = map.get("uid");
                        break;
                }

                //昵称
                String nickname = map.get("name");
                //第三方账号绑定
                getBindingQQWechatWeiBo(type, open, nickname);
            } else {
                mShareAPI.getPlatformInfo(ThirdBindingActivity.this, share_media, authListener);
            }
        }

        @Override
        public void onError(SHARE_MEDIA share_media, int i, Throwable throwable) {
            toast(throwable.getMessage().toString());
        }

        @Override
        public void onCancel(SHARE_MEDIA share_media, int i) {
            toast("用户取消了");
        }
    };

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        mShareAPI.onActivityResult(requestCode, resultCode, data);
    }

    /**
     * 第三方账户绑定 回调
     */
    @Override
    public void onThirdBind(INetBean bean) {
        if (bean.getErrCode() == 0) {
            getThirdParty();
        } else {
            toast(bean.getErrMsg());
        }
    }

    /**
     * 第三方账户解绑 回调
     */
    @Override
    public void onThirdUnBind(INetBean bean) {
        if (bean.getErrCode() == 0) {
            getThirdParty();
            mShareAPI.deleteOauth(this, type == 1 ? SHARE_MEDIA.QQ : type == 2 ? SHARE_MEDIA.WEIXIN : SHARE_MEDIA.SINA, authListener);
        } else {
            toast(bean.getErrMsg());
        }
    }

    /**
     * 获取第三方账号绑定信息和实名认证信息 回调
     */
    @Override
    public void onThirdPartyInfo(ThirdPartyInfo info) {
        if (info.getErrCode() == 0) {
            bean = info.getResponse();
            if (bean != null) {
                //bound_qq_gray_icon
                isBoundQQ = TextUtils.isEmpty(bean.getQq()) ? false : true;
                //bound_weixin_gray_icon
                isBoundWX = TextUtils.isEmpty(bean.getWechat()) ? false : true;
                //xinlang
                isBoundXL = TextUtils.isEmpty(bean.getWeibo()) ? false : true;
                //update
                refreshView();
            }
        } else {
            toast(info.getErrMsg());
        }
    }
}
